﻿#include "ListDirResponsePrivate.h"
#include "qftp.h"
#include "ListDirResponse.h"
#include "ZFtpUtils.h"
#include <QTextCodec>
#include <QVector>

BEGIN_NAMESPACE_ZFTPNS

ListDirResponsePrivate::ListDirResponsePrivate(QObject *parent) :
    ZFtpResponsePrivate(parent),
    q_ptr(NULL)
{

}

void ListDirResponsePrivate::listenTo(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> ftp_config)
{
    ZFtpResponsePrivate::listenTo(ftp, ftp_config);

    if (!ftp) return;
    ftp->disconnect(this, SLOT(slotCommandFinished(int,bool)));
    ftp->disconnect(this, SLOT(slotListInfo(QUrlInfo)));
    ftp->disconnect(this, SLOT(slotFtpStateChanged(int)));

    connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));
    connect(ftp.data(), SIGNAL(listInfo(QUrlInfo)), SLOT(slotListInfo(QUrlInfo)));
    connect(ftp.data(), SIGNAL(stateChanged(int)), SLOT(slotFtpStateChanged(int)));

    m_ftp_config = ftp_config;
}

void ListDirResponsePrivate::setPublicResponseObject(QPointer<ZFtpResponse> response)
{
    ZFtpResponsePrivate::setPublicResponseObject(response);
    q_ptr = qobject_cast<ListDirResponse *>(response.data());
    Q_ASSERT(q_ptr);
}

QPointer<ZFtpResponse> ListDirResponsePrivate::publicObject()
{
    return QPointer<ZFtpResponse>(q_ptr);
}

void ListDirResponsePrivate::slotCommandFinished(int id, bool error)
{
    if (this->ftpTaskID() != id) return;
    invalidFtpTaskID();

    Q_ASSERT(q_ptr);
    emit q_ptr->sigResult(!error);
}

void ListDirResponsePrivate::slotListInfo(QUrlInfo info)
{
    Q_ASSERT(q_ptr);
    if (m_ftp_config)
    {
        // 进行编码转换
        QTextCodec *ftp_textcodec = m_ftp_config->ftpServerTextCodec();
        Q_ASSERT(ftp_textcodec);

        // 将包裹某编码格式数据的QString中的数据原封不动取出来，进行编码转换
        QString coded_name = ZFtpUtils::fromTextCodecString(ftp_textcodec, info.name());
        info.setName(coded_name);
        emit q_ptr->sigListInfo(info);
    }
    else
    {
        emit q_ptr->sigListInfo(info);
    }
}

void ListDirResponsePrivate::slotFtpStateChanged(int state)
{
}

END_NAMESPACE
